package xxl.robotlegs.extensions.modularity.impl 
{
	import flash.display.DisplayObjectContainer;
	import xxl.robotlegs.extensions.viewmanager.api.IViewManager;
	import xxl.robotlegs.extensions.viewmanager.impl.ViewManagerSignal;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.ILogger;
	/**
	 * ...
	 * @author XXL
	 */
	public class ViewManagerBasedExistenceWatcher 
	{
		private var _context:IContext;
		private var _viewManager:IViewManager;
		private var _logger:ILogger;
		
		public function ViewManagerBasedExistenceWatcher(context:IContext, viewManager:IViewManager) 
		{
			_context = context;
			_viewManager = viewManager;
			_logger = context.getLogger(this);
			context.whenDestroying(destroy);
			init();
		}
		
		private function init():void 
		{
			const containers:Vector.<DisplayObjectContainer> = _viewManager.containers;
			const len:int = containers.length;
			for (var i:int = 0; i < len; i++) 
			{
				const container:DisplayObjectContainer = containers[i];
				_logger.debug("在容器 {0} 上添加了一个context是否存在的监听", [container]);
				container.addEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
			}
			_viewManager.signal.addToMap(ViewManagerSignal.CONTAINER_ADD, onContainerAdd).safelyExecute = true;
			_viewManager.signal.addToMap(ViewManagerSignal.CONTAINER_REMOVE, onContainerRemove).safelyExecute = true;
		}
		
		private function destroy():void 
		{
			const containers:Vector.<DisplayObjectContainer> = _viewManager.containers;
			const len:int = containers.length;
			for (var i:int = 0; i < len; i++) 
			{
				const container:DisplayObjectContainer = containers[i];
				_logger.debug("在容器 {0} 上删除一个context是否存在的监听", [container]);
				container.removeEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
			}
			_viewManager.signal.removeFromMap(ViewManagerSignal.CONTAINER_ADD, onContainerAdd);
			_viewManager.signal.removeFromMap(ViewManagerSignal.CONTAINER_REMOVE, onContainerRemove);
		}
		
		private function onContainerRemove(type:String, container:DisplayObjectContainer):void 
		{
			_logger.debug("在容器 {0} 上删除一个context是否存在的监听", [container]);
			container.removeEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
		}
		
		private function onContainerAdd(type:String, container:DisplayObjectContainer):void 
		{
			_logger.debug("在容器 {0} 上添加了一个context是否存在的监听", [container]);
			container.addEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
		}
		
		private function onContextAdd(event:ModularContextEvent):void
		{
			const context:IContext = event.context;
			if (context != _context)
			{
				event.stopImmediatePropagation();
				_logger.debug("配置子context {0}", [context]);
				_context.addChild(context);
			}
		}
		
	}

}